package br.com.checkandgo.util;

import java.util.Locale;

import br.com.checkandgo.MainActivity;
import br.com.checkandgo.model.PontosRota;
import br.com.checkandgo.model.Route;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;

public class RotaAsyncTask extends AsyncTask<Double, Void, Void>{

	private GoogleMap mapView;
	private Context context;
	private PontosRota pontos;
	private MainActivity main;

	public RotaAsyncTask(Context ctx, GoogleMap mapa, MainActivity m, PontosRota p) {
		mapView = mapa;
		context = ctx;
		main = m;
		pontos = p;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Void doInBackground(Double... params) {
		PontosRota newRoute = directions(new LatLng(params[0], params[1]), new LatLng(params[2], params[3]));
		pontos.addPoints(newRoute.getPoints());
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		PolylineOptions options = new PolylineOptions()
		.width(4)
		.color(Color.RED)
		.visible(true);

		for (LatLng latlng : pontos.getPoints()) {
			options.add(latlng);
		}
		mapView.addPolyline(options);
	}

	private PontosRota directions(final LatLng start, final LatLng dest) {

		// Formatando a URL com a latitude e longitude  
		// de origem e destino.  
		String urlRota = String.format(Locale.US,
				"http://maps.googleapis.com/maps/api/"+
						"directions/json?origin=%f,%f&"+
						"destination=%f,%f&" +
						"sensor=true&mode=driving",   
						start.latitude, 
						start.longitude, 
						dest.latitude, 
						dest.longitude); 

		GoogleParser parser = new GoogleParser(urlRota);
		return parser.parse();
	}
}